<?php
/*
 * 商品分类
 */
namespace app\admin\controller;
use app\common\controller\AdminBase;
use think\facade\Db;
use app\common\model\GoodGroup as GoodGroupModel;

class GoodGroup extends AdminBase
{
    public function lists()
    {
        $param = $this->request->param();
        if (!empty($param['title'])) {
            $where = function ($query) use ($param){$query->where('name','LIKE', '%'.trim($param['title']).'%');};
        }else{
            $where = 1;
        }
        $list = GoodGroupModel::where($where)->paginate();
        foreach ($list as $key => $v) {
            $sku_id = Db::table('sku')->whereIn('id',$v['sku_id'])->column('name');
            $list[$key]['sku_name'] = $sku_id;
        }
        return $this->fetch('index',['list'=>$list]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['sku_id'] = implode(',',$param['sku_id']);
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'good_group');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $result = GoodGroupModel::create($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('添加了商品模型');
            $this->success('添加成功');
        }
        return $this->fetch('save',['list' => Db::table('sku')->where(['status'=>1,'pid'=>0])->select()]);
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['sku_id'] = implode(',',$param['sku_id']);
            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'good_group');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $result = GoodGroupModel::update($param);
            !$result && $this->error($this->errorMsg);
            insert_admin_log('修改了商品模型');
            $this->success('修改成功');
        }
        return $this->fetch('save',['list' => Db::table('sku')->where(['status'=>1,'pid'=>0])->select(),'data' => Db::table('good_group')->find(input('id'))]);
    }

    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            Db::table('goods')->where('group_id',$param['id'])->find() && $this->error('商品正在使用该商品模型，无法删除');
            GoodGroupModel::destroy($param['id']);
            insert_admin_log('删除了商品模型');
            $this->success('删除成功');
        }
    }



}
